<?php namespace system\model;

use hdphp\Model\Model;

class User extends Model{

	//数据表****************
	protected $table = "user";

	//完整表名
	protected $full = false;

	//自动验证************
	protected $validate=[
		//['字段名','验证方法','提示信息',验证条件,验证时间]
		//表单name跟数据库字段保持一致
		['username','required','用户名不能为空',self::MUST_VALIDATE,self::MODEL_BOTH],
		['password','required','密码不能为空',self::MUST_VALIDATE,self::MODEL_BOTH],
	];
	//自动完成
	protected $auto=[
		//['字段名','处理方法','方法类型',验证条件,验证时机]
	];
	//时间操作,需要表中存在created_at,updated_at字段
	protected $timestamps=false;
	//检测用户是否登陆
	public function isLogin()
	{
		//自动验证,如果验证不通过，return false;
		if(!$this->create()) return false;
		$data = $_POST;
		//比对验证码是否正确
//		if(strtoupper($_POST['code'])!= $_SESSION['code']){
		if(strtoupper($_POST['code'])!= Code::get()){
			//进行错误提示
			//将错误信息存储到模型error属性中
			$this->error = '验证码错误';
			return false;
		}
		//比对用户名和密码是否正确
		//select * from user  where username='' and password='';
		$data = $this->where('username',$data['username'])
				->where('password',Crypt::encrypt($data['password']))->first();
		//p($data);die;
		//[]
		if(!$data){
			//用户名或者密码不正确
			$this->error = '用户名或者密码不正确';
			return false;
		}
		//能走到这里说明用户名密码以及验证码都正确
		$_SESSION['admin']['uid'] = $data['uid'];
		$_SESSION['admin']['username'] = $data['username'];
		return true;
	}

	/**
	 * 修改密码
	 */
	public function changePass(){
		//p($_POST);die;
		$data = $_POST;
		//1.验证原始密码是否正确Crypt::encrypt($data['password'])
		//获取单一列数据
		$passwd = $this->where('uid',$_SESSION['admin']['uid'])->pluck('password');
		if($passwd!=Crypt::encrypt($data['password'])){
			$this->error = '原始密码不正确';
			return false;
		}
		//2.新密码以及确认密码是否一致
		if(!trim($data['new_password'])){
			$this->error = '新密码不能为空';
			return false;
		}
		if($data['new_password']!=$data['confirm_password']){
			$this->error = '两次密码不一致';
			return false;
		}
		//3.进行密码修改
		$this->where('uid',$_SESSION['admin']['uid'])->update(['password' => Crypt::encrypt($data['new_password'])]);
		return true;
	}

}